package com.bsoft.servicetest;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.socks.library.KLog;

/**
 * Created by 泅渡者
 * Created on 2017/9/20.
 */

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_start, btn_stop, btn_bind, btn_unbind;
    private MyService.MyBinder myBinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_start = (Button) findViewById(R.id.btn_start);
        btn_stop = (Button) findViewById(R.id.btn_stop);
        btn_bind = (Button) findViewById(R.id.btn_bind);
        btn_unbind = (Button) findViewById(R.id.btn_unbind);

        btn_start.setOnClickListener(this);
        btn_stop.setOnClickListener(this);
        btn_bind.setOnClickListener(this);
        btn_unbind.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_start:
                Intent startIntent = new Intent(this, WeatherService.class);
                startService(startIntent);
                break;
            case R.id.btn_stop:
                Intent stopIntent = new Intent(this, MyService.class);
                stopService(stopIntent);
                break;
            case R.id.btn_bind:
                /**
                 * 1).Context.BIND_AUTO_CREATE
                 *说明：表示收到绑定请求的时候，如果服务尚未创建，则即刻创建，在系统内存不足需要先摧毁优先级组件来释放内存，且只有驻留该服务的进程成为被摧毁对象时，服务才被摧毁
                 *2).Context.BIND_DEBUG_UNBIND
                 *说明：通常用于调试场景中判断绑定的服务是否正确，但容易引起内存泄漏，因此非调试目的的时候不建议使用
                 *3).Context.BIND_NOT_FOREGROUND
                 *说明：表示系统将阻止驻留该服务的进程具有前台优先级，仅在后台运行，该标志位位于Froyo中引入。
                 */
                Intent bindIntent = new Intent(this, WeatherService.class);
                bindService(bindIntent, connection, BIND_AUTO_CREATE);
                break;
            case R.id.btn_unbind:
                unbindService(connection);
                break;
        }

    }

    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            KLog.d("Service 没有链接");
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            KLog.d("Service 已经链接");
            myBinder = (MyService.MyBinder) service;
            myBinder.Download();
        }

    };

}
